//================================================================================================================================
//
//  Copyright (c) 2015-2018 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
//  EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
//  and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//================================================================================================================================

package cn.easyar.samples.helloarqrcode;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yiwent.viewlib.ShiftyTextview;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import cn.easyar.Engine;
import cn.easyar.samples.helloarqrcode.bean.DataBean;
import cn.easyar.samples.helloarqrcode.bean.EquipmentMessage;
import cn.easyar.samples.helloarqrcode.bean.QRcodeMessage;
import cn.easyar.samples.helloarqrcode.remote.SelectListActivity;
import cn.easyar.samples.helloarqrcode.util.JiangeUtil;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceBean;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceOrder;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceService;
import io.reactivex.functions.Consumer;


public class MainActivity extends AppCompatActivity
{
    /*
    * Steps to create the key for this sample:
    *  1. login www.easyar.com
    *  2. create app with
    *      Name: HelloARQRCode
    *      Package Name: cn.easyar.samples.helloarqrcode
    *  3. find the created item in the list and show key
    *  4. set key string bellow
    */
    private static String key = "MbHMbRwIB0aftiTFH2sSt2SoRI7o42qHzVXjO84or1PRgvC5hIpfkQ9S4Ii5nxe3Ch4IiLw7bvINcc8sXmNbutZbjjGYUBeJ8SyFCLlndS3B7WBuSbNBPhJ9dtAS9DcvBWIcEQKxKsSFoJ6LieeDGVS1d9laWcmnNMSvy4ERRzVfd39iDVnyjH3zc4sIiCEG9biuhTaK";
    private GLView glView;
    private LinearLayout ll_qrcode_view;
    private QRcodeHideControl qRcodeHideControl;
    private TextView tv_qrcode_text;
    private LinearLayout ll_equipment_view;
    private EquipmentHideControl equipmentHideControl;
    private DataBean dataBean1;
    private DataBean dataBean2;
    private DataBean dataBean3;
    private ShiftyTextview text3;
    private String equipmentName = "";
    private String qrcode_msg = "";
    private TextView tv_up_text;
    private TextView tv_up_finish;
    private LinearLayout ll_warning_info;
    private Button btn_dcs;
    private Button btn_analysis;
    private Button btn_remote;
    private RelativeLayout rl_normal_info;
    private float currentScale = 1.0f;
    private float oldScale = 1.0f;
    private LinearLayout ll_patrol_form;
    private boolean xunjianFlag1 = false;
    private int xunjianFlag2 = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().register(this);
        VoiceOrder.activityList.add("MainActivity");
        ll_qrcode_view = (LinearLayout) findViewById(R.id.ll_qrcode_view);
//        tv_qrcode_text = (TextView) findViewById(R.id.tv_qrcode_text);
        ll_equipment_view = (LinearLayout) findViewById(R.id.ll_equipment_view);
        text3 = (ShiftyTextview) findViewById(R.id.text3);
        tv_up_text = (TextView) findViewById(R.id.tv_up_text);
        tv_up_finish = (TextView) findViewById(R.id.tv_up_finish);
        rl_normal_info = (RelativeLayout) findViewById(R.id.rl_normal_info);
        ll_warning_info = (LinearLayout) findViewById(R.id.ll_warning_info);
        btn_dcs = (Button) findViewById(R.id.btn_dcs);
        btn_analysis = (Button) findViewById(R.id.btn_analysis);
        btn_remote = (Button) findViewById(R.id.btn_remote);
        ll_patrol_form = findViewById(R.id.ll_patrol_form);
        btn_dcs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(MainActivity.this, DCSActivity.class);
                startActivity(it);
            }
        });

        btn_analysis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(MainActivity.this, AnalysisActivity.class);
                startActivity(it);
            }
        });

        ll_patrol_form.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(MainActivity.this, PatrolResultActivity.class);
                startActivity(it);
            }
        });

//        Intent it = new Intent(MainActivity.this, SelectListActivity.class);
//        startActivity(it);

        qRcodeHideControl = new QRcodeHideControl();
        equipmentHideControl = new EquipmentHideControl();

        dataBean1 = new DataBean("450", "220", "1.2");
        dataBean2 = new DataBean("540", "220", "3.0");
        dataBean3 = new DataBean("555", "340", "0.0");



        if (!Engine.initialize(this, key)) {
            Log.e("HelloAR", "Initialization Failed.");
        }

        glView = new GLView(this);

        requestCameraPermission(new PermissionCallback() {
            @Override
            public void onSuccess() {
                ((ViewGroup) findViewById(R.id.preview)).addView(glView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }

            @Override
            public void onFailure() {
            }
        });
        checkPermissions();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanQRcode(QRcodeMessage message) {
        if (ll_equipment_view.getVisibility() == View.VISIBLE) {
            ll_equipment_view.setVisibility(View.GONE);
        }
        ll_qrcode_view.setVisibility(View.VISIBLE);
//        tv_qrcode_text.setText("正在巡检"+message.message);
        qRcodeHideControl.startHideTimer();

        /*设置动画*/
        Animation animation_top = AnimationUtils.loadAnimation(this,R.anim.anim_slide_out_from_top);
        animation_top.setInterpolator(new DecelerateInterpolator());
        animation_top.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        if (!qrcode_msg.equals(message.message)) {
            ll_qrcode_view.clearAnimation();
            ll_qrcode_view.startAnimation(animation_top);
            qrcode_msg = message.message;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void voiceEvent(VoiceBean voiceBean) {
        if(voiceBean.str.contains(VoiceOrder.VOICE_FOCUSING)){
            focusIng();
        }else if(voiceBean.str.contains(VoiceOrder.VOICE_REDUCTION)){
            focusReduction();
        }else if(voiceBean.str.contains(VoiceOrder.VOICE_SEE_DCS)){
            Intent it = new Intent(MainActivity.this, DCSActivity.class);
            startActivity(it);
        }else if(voiceBean.str.contains(VoiceOrder.VOICE_ABNORMAL)){
            Intent it = new Intent(MainActivity.this, AnalysisActivity.class);
            startActivity(it);
        }else if(voiceBean.str.contains(VoiceOrder.VOICE_GUIDANCE)){
            Intent it = new Intent(MainActivity.this, SelectListActivity.class);
            startActivity(it);
        }
    }

    private void focusIng(){
        if(currentScale<5.0f){
            currentScale += 1.0f;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ValueAnimator anim = ValueAnimator.ofFloat(oldScale, currentScale);
                    anim.setDuration(600);
                    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float currentValue = (float) animation.getAnimatedValue();
                            glView.setScale(currentValue);
                        }
                    });
                    anim.start();
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            oldScale = currentScale;
                        }
                    });
                }
            });
        }else{
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "当前已经是最大了", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void focusReduction(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ValueAnimator anim = ValueAnimator.ofFloat(currentScale, 1f);
                anim.setDuration(600);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float currentValue = (float) animation.getAnimatedValue();
                        glView.setScale(currentValue);
                    }
                });
                anim.start();
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        currentScale = 1f;
                        oldScale = 1f;
                    }
                });
            }

        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanEquipment(final EquipmentMessage message) {
        //判断正常和异常页面
        if (message.message.equals("argame")) {//正常页面
            rl_normal_info.setVisibility(View.VISIBLE);
            ll_warning_info.setVisibility(View.GONE);
            xunjianFlag1 = true;

        } else if (message.message.equals("argame01")||message.message.equals("argame02")){//异常页面
            rl_normal_info.setVisibility(View.GONE);
            ll_warning_info.setVisibility(View.VISIBLE);
            xunjianFlag2 ++;
        }

        if (ll_qrcode_view.getVisibility() == View.VISIBLE) {
            ll_qrcode_view.setVisibility(View.GONE);
        }

        Log.i("", "scanEquipment: ");


        Animation animation_right = AnimationUtils.loadAnimation(this,R.anim.anim_right);
        animation_right.setInterpolator(new DecelerateInterpolator());
        animation_right.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (message.message.equals("argame")) {
                    text3.setNumberString(dataBean1.data3);
                    text3.setTextColor(Color.parseColor("#66CD00"));

                } else if (message.message.equals("argame01")) {
                    text3.setNumberString(dataBean2.data3);
                    text3.setTextColor(Color.parseColor("#CD2626"));

                } else if (message.message.equals("argame02")) {
                    text3.setNumberString(dataBean3.data3);
                    text3.setTextColor(Color.parseColor("#CD2626"));
                }

                if (xunjianFlag1 && xunjianFlag2>=2) {
                    ll_patrol_form.setVisibility(View.VISIBLE);
                }

                tv_up_text.setVisibility(View.VISIBLE);
                JiangeUtil jiangeUtil = new JiangeUtil(tv_up_text, "数据上传中...", 500);
                jiangeUtil.setOnLoadFinishListener(new JiangeUtil.OnLoadFinishListener() {
                    @Override
                    public void onLoadFinish() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_up_text.setVisibility(View.GONE);
                                tv_up_finish.setVisibility(View.VISIBLE);

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                tv_up_finish.setVisibility(View.GONE);
                                            }
                                        });

                                    }
                                },2000);
                            }
                        });

                    }
                });


            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        if (!equipmentName.equals(message.message)){
            ll_equipment_view.clearAnimation();
            ll_equipment_view.setAnimation(animation_right);
            equipmentName = message.message;
        }




        ll_equipment_view.setVisibility(View.VISIBLE);
        equipmentHideControl.startHideTimer();

    }



    private interface PermissionCallback
    {
        void onSuccess();
        void onFailure();
    }
    private HashMap<Integer, PermissionCallback> permissionCallbacks = new HashMap<Integer, PermissionCallback>();
    private int permissionRequestCodeSerial = 0;
    @TargetApi(23)
    private void requestCameraPermission(PermissionCallback callback)
    {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                int requestCode = permissionRequestCodeSerial;
                permissionRequestCodeSerial += 1;
                permissionCallbacks.put(requestCode, callback);
                requestPermissions(new String[]{Manifest.permission.CAMERA}, requestCode);
            } else {
                callback.onSuccess();
            }
        } else {
            callback.onSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (permissionCallbacks.containsKey(requestCode)) {
            PermissionCallback callback = permissionCallbacks.get(requestCode);
            permissionCallbacks.remove(requestCode);
            boolean executed = false;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    executed = true;
                    callback.onFailure();
                }
            }
            if (!executed) {
                callback.onSuccess();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (glView != null) { glView.onResume(); }
    }

    @Override
    protected void onPause()
    {
        if (glView != null) { glView.onPause(); }
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent stopIntent = new Intent(this, VoiceService.class);
        stopService(stopIntent);
        EventBus.getDefault().unregister(this);
    }

    public class QRcodeHideControl {
        public final static int MSG_HIDE = 0x01;

        private HideHandler mHideHandler;

        public QRcodeHideControl() {
            mHideHandler = new HideHandler();
        }

        public class HideHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_HIDE:
                        ll_qrcode_view.setVisibility(View.INVISIBLE);
                        break;

                }

            }
        }

        private Runnable hideRunable = new Runnable() {

            @Override
            public void run() {
                mHideHandler.obtainMessage(MSG_HIDE).sendToTarget();
            }
        };

        public void startHideTimer() {//开始计时,三秒后执行runable
            mHideHandler.removeCallbacks(hideRunable);
            if(ll_qrcode_view.getVisibility() == View.INVISIBLE){
                ll_qrcode_view.setVisibility(View.VISIBLE);
            }
            mHideHandler.postDelayed(hideRunable, 3000);
        }

        public void endHideTimer() {//移除runable,将不再计时
            mHideHandler.removeCallbacks(hideRunable);
        }

        public void resetHideTimer() {//重置计时
            mHideHandler.removeCallbacks(hideRunable);
            mHideHandler.postDelayed(hideRunable, 3000);
        }

    }

    public class EquipmentHideControl {
        public final static int MSG_HIDE = 0x02;

        private HideHandler mHideHandler;

        public EquipmentHideControl() {
            mHideHandler = new HideHandler();
        }

        public class HideHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_HIDE:
                        ll_equipment_view.setVisibility(View.INVISIBLE);
                        break;

                }

            }
        }

        private Runnable hideRunable = new Runnable() {

            @Override
            public void run() {
                mHideHandler.obtainMessage(MSG_HIDE).sendToTarget();
            }
        };

        public void startHideTimer() {//开始计时,三秒后执行runable
            mHideHandler.removeCallbacks(hideRunable);
            if(ll_equipment_view.getVisibility() == View.INVISIBLE){
                ll_equipment_view.setVisibility(View.VISIBLE);
            }
            mHideHandler.postDelayed(hideRunable, 5000);
        }

        public void endHideTimer() {//移除runable,将不再计时
            mHideHandler.removeCallbacks(hideRunable);
        }

        public void resetHideTimer() {//重置计时
            mHideHandler.removeCallbacks(hideRunable);
            mHideHandler.postDelayed(hideRunable, 5000);
        }

    }

    //----------------------------------------------------

    private void checkPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Intent startIntent = new Intent(MainActivity.this, VoiceService.class);
                            startService(startIntent);
                        } else {

                        }
                    }
                });
    }

}

